<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 用戶接口
 */
class User extends Api
{
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        

    }

    /**
     * 用戶信息
     */
    public function info()
    {
        $user = $this->auth->getUserinfo();
        $this->success('ok', $user);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    public function setting(){
        $name = $this->request->post('send_name');
        $email = $this->request->post('send_email');
        if(empty($name)){
            $this->error(__('Please enter the sender\'s name'));
        }
        if(empty($email) || !Validate::is($email, 'email')){
            $this->error(__('Please enter the sender\'s email'));
        }
        $template = $this->request->post('template');
        $result = model('User')->where(['id' => $this->auth->id])->update([
            'send_email_name' => $name,
            'send_from_email' => $email,
            'email_temp'        => $template
        ]);
        $this->success(__('save successful'));
    }
    /**
     * 獲取當前用戶的郵件模板
     */
    public function email_template(){
        $user = $this->auth->getUserinfo();
        $template = str_replace("{name}",$user['send_email_name'],$user['email_temp']);
        $this->success('ok', ['template' => $template]);
    }
}
